<?php

namespace app\admin\controller\xiservice;

use app\common\controller\Backend;
use app\common\model\xiservice\Schedule as ScheduleModel;
use app\common\model\xiservice\Timelist;
use app\common\model\xiservice\Order as OrderModel;
use think\Db;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class User extends Backend
{

    /**
     * User模型对象
     * @var \app\common\model\xiservice\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\xiservice\User;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where('group_id', 1)
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $cur_userid = $row['user_id'];
                $order_count= Db::name('xiservice_order')->where('user_id',$cur_userid)->where('order_status',0)->count();
                $row['cancel_num']=$order_count;

                $row->visible(['id','cancel_num', 'username', 'avatar', 'mobile', 'order_num', 'order_money', 'status', 'createtime']);

            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 查询符合条件的服务人员
     */

    public function worker()
    {
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            if ($this->request->request('keyValue')) {
                return $this->selectpage();
            }
            $order_id = $this->request->request('order_id');
            $order = orderModel::with(['service'])->where('order.id', $order_id)->find();
            $serviceCategoryId = $order['service']['service_category_id'];
            $lat = $order['lat'];
            $lng = $order['lng'];
            $reserve_time = $order['service_start_time'];
            $duration_time = $order['service_duration'];

            $distance = isset(config('xiservice.order')['auto_distance']) ? config('xiservice.order')['auto_distance'] * 1000 : 5000;
            //根据经纬度检索服务人员
            $list = $this->model->where('group_id', 2)
                ->where('FIND_IN_SET(:id,service_category_id)', ['id' => $serviceCategoryId])
                ->where('work_status', 1)
                ->where('status', 1)
                ->where('checkinfo', 1)
                ->field("*,(6378.138 * 2 * asin(sqrt(pow(sin((lat * pi() / 180 - " . $lat . " * pi() / 180) / 2),2) + cos(lat * pi() / 180) * cos(" . $lat . " * pi() / 180) * pow(sin((lng * pi() / 180 - " . $lng . " * pi() / 180) / 2),2))) * 1000) as distance")
                ->having("distance < {$distance}")
                ->order('distance asc')
                ->select();
            if (!$list) {
                $result = array("total" => 0, "rows" => []);
                return json($result);
            }
            $count = $duration_time / 30;
            //时间分段
            $time_arr = [];
            array_push($time_arr, $reserve_time);
            if ($count > 1) {
                for ($i = 0; $i < $count; $i++) {
                    $time = $reserve_time + 30 * 60 * ($i + 1);
                    array_push($time_arr, $time);
                }
            } else {
                array_push($time_arr, $reserve_time + 30 * 60);
            }
            //判断服务人员时间上是否冲突
            $member = [];
            for ($i = 0; $i < count($list); $i++) {
                $check = ScheduleModel::where('user_id', $list[$i]['id'])->where('rest_timestamp', 'in', $time_arr)->find();
                if (!$check) {
                    array_push($member, $list[$i]);
                }
            }


            $result = array("total" => count($member), "rows" => $member, 'order_id' => $order_id);

            return json($result);
        } else {
            $result = array("total" => 0, "rows" => []);
            return json($result);
        }
    }

    public function bluckone($ids){
        $ids = $this->request->request('ids');
       
        $map = Db::name('xiservice_user')->where('id',$ids)->find();

        $row['status'] = 0;
        $ruesle['status'] = 'hidden';
        $res = Db::name('xiservice_user')->where('id',$ids)->update($row);
        $res1 = Db::name('user')->where('id',$map['user_id'])->update($ruesle);
        echo "<pre>";
        print_r($res1);die;

        if($res){
            $this->success('拉黑成功');
        }else{
            $this->error('拉黑失败');
        }
    }
    /**
     * 转为业务员
     * @param $ids
     * @param $gid
     * @throws \think\exception\DbException
     */
    public function setgroup($ids, $gid)
    {
        $row = $this->model->get($ids);
        $row->group_id = $gid;
        $row->save();
        $this->success();
    }

}
